package com.xiaowan.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@MapperScan("com.xiaowan.**.dao") // mybatis
@ComponentScan(basePackages = {"com.xiaowan.**.service", "com.xiaowan.**.aop"},
        excludeFilters = @ComponentScan.Filter(Controller.class)) // 扫描service类,排除@Controller注解的类
@EnableTransactionManagement // 开启mybatis事务
@PropertySource("classpath:db.properties")
@EnableAspectJAutoProxy(proxyTargetClass = true) // 设置为true将类改为cglib代理模式,这里也可以为false，毕竟service层是接口，可以使用jdk代理或者cglib代理
public class AppConfig {

    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    /**
     * @Description 配置Mybatis SqlSession
     * @Author wbm
     * @return org.apache.ibatis.session.SqlSessionFactory
     **/
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(druidDataSource());
        return factoryBean.getObject();
    }


    /**
     * @Description 开启事务管理
     * @Author wbm
     * @return org.springframework.jdbc.datasource.DataSourceTransactionManager
     **/
    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(druidDataSource());
    }


    /**
     * @Description 配置数据库
     * @Author wbm
     * @return com.alibaba.druid.pool.DruidDataSource
     **/
    @Bean
    public DruidDataSource druidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        return dataSource;
    }
}
